package com.jcf.springboot.security.filter;

import com.alibaba.fastjson.JSON;
import com.jcf.springboot.common.R;
import com.jcf.springboot.security.util.JwtConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ${chaofan.ji}
 * @since 2023/4/22
 */

@Component
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {


  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    log.error(authException.getMessage());
    System.out.println(authException.getMessage());
    response.setContentType("application/json;charset=UTF-8");
    ServletOutputStream outputStream = response.getOutputStream();

    String errMsg = authException.getMessage();
    if (JwtConstant.JWT_ERRCODE_EXPIRE ==  response.getStatus())
    {
      errMsg = "token失效，请重新登录";
    }
    else if(JwtConstant.JWT_ERRCODE_FAIL == response.getStatus()){
      errMsg = "认证失败，请重新登录";
    }
    else if(JwtConstant.JWT_USERNAME_CHANGED == response.getStatus()){
      errMsg = "账户名已被修改，请重新登录";
    }

    R error = R.ok().code(response.getStatus()).message(errMsg);
    response.setStatus(HttpServletResponse.SC_OK);
    outputStream.write(JSON.toJSONString(error).getBytes("UTF-8"));
    outputStream.flush();
    outputStream.close();
  }
}
